package com.baseandroid;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.BounceInterpolator;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.androidbase.base.BaseApplication;
import com.androidbase.oklog.debug.DebugInfoActivity;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.config.Api;
import com.baseandroid.config.Global;
import com.baseandroid.dagger.component.DaggerMyAppComponent;
import com.baseandroid.dagger.component.MyAppComponent;
import com.baseandroid.dagger.module.MyAppModule;
import com.baseandroid.gaode.GaoDeMap;
import com.baseandroid.push.TimeConstants;
import com.qianbao.mobilecashier.QBCashier;
import com.qianbao.qianbaobusiness.BuildConfig;
import com.qianbao.qianbaobusiness.R;
import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.Screen;

import cn.jpush.android.api.JPushInterface;
import timber.log.Timber;
import today.youcanbe.scansdk.ScanSdk;

public class MyApplication extends BaseApplication {

    private static MyAppComponent mMyAppComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        setDebugMode(BuildConfig.DEBUG);

        initMyAppInject(this);

        Api.setEnviroment(BuildConfig.APP_ENV);

        if (Api.isDevelop) {
            CrashReport.initCrashReport(this, "4794ad8c82", true);
        } else {
            CrashReport.initCrashReport(this, "c6d1eaca6c", true);
        }

        GaoDeMap.getInstance().init(this);

        //初始化人脸识别sdk
        ScanSdk.initSdk(this, "ea40ad1cf0174bf7bdddfc3a9da12ea6", "64377802526d4a22aad487637de044f9");
        //初始化收银台sdk
        QBCashier.init(this);
        /*--极光初始化--*/
        JPushInterface.init(this);
        /*--阿里初始化--*/
        initAliCloudPush(this);
        /*--设置默认的Push--*/
        setdefaultPush(this);
        /*--记录App启动时间--*/
        TimeConstants.getInstance().setAppLaunchTS(System.currentTimeMillis());
    }

    public static void initAliCloudPush(Application applicationContext) {
        PushServiceFactory.init(applicationContext);
        final CloudPushService pushService = PushServiceFactory.getCloudPushService();
        if (Api.isDevelop) {
            pushService.register(applicationContext, "24932947", "58da8712a0d8af7a1b1ce6d6f4a51569", new CommonCallback() {
                @Override
                public void onSuccess(String response) {
                    Timber.e("init cloudchannel success");
                    Timber.e("deviceId = " + pushService.getDeviceId());
                    Timber.e("Push Alias = " + pushService.getDeviceId());
                }

                @Override
                public void onFailed(String errorCode, String errorMessage) {
                    Timber.e("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
                }
            });
        } else {
            pushService.register(applicationContext, "24839876", "0a2966d074b8261636420f4920ac5460", new CommonCallback() {
                @Override
                public void onSuccess(String response) {
                    Timber.e("init cloudchannel success");
                    Timber.e("deviceId = " + pushService.getDeviceId());
                }

                @Override
                public void onFailed(String errorCode, String errorMessage) {
                    Timber.e("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
                }
            });
        }

        MiPushRegister.register(applicationContext, "2882303761517387966", "5971738727966");
        HuaWeiRegister.register(applicationContext);
    }

    private void setdefaultPush(Application applicationContext) {
        if (!TextUtils.isEmpty(Global.getPushConfig()) && Global.getPushConfig()
                .equals("1")) {
            JPushInterface.stopPush(applicationContext);
            PushServiceFactory.getCloudPushService()
                    .turnOnPushChannel(new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {
                            Log.e("turnOnPushChannel", "turnOnPushChannel success");
                        }

                        @Override
                        public void onFailed(String s, String s1) {
                            Log.e("turnOnPushChannel", "init turnOnPushChannel onFailed");
                        }
                    });
        } else {
            JPushInterface.resumePush(applicationContext);
            PushServiceFactory.getCloudPushService()
                    .turnOffPushChannel(new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {
                            Log.e("turnOffPushChannel", "turnOnPushChannel success");
                        }

                        @Override
                        public void onFailed(String s, String s1) {
                            Log.e("turnOffPushChannel", "turnOnPushChannel onFailed");
                        }
                    });
        }
    }

    public void initMyAppInject(Context context) {
        mMyAppComponent = DaggerMyAppComponent.builder().
                appComponent(getAppComponent()).myAppModule(new MyAppModule()).build();
    }

    public static MyAppComponent getMyAppComponent() {
        return mMyAppComponent;
    }

    public static String getAppVersionName(Application application) {
        if (application != null) {
            PackageManager pm = application.getPackageManager();
            if (pm != null) {
                PackageInfo pi;
                try {
                    pi = pm.getPackageInfo(application.getPackageName(), 0);
                    if (pi != null) {
                        return pi.versionName;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //阿里热修复初始化工作以及如果本地有补丁的话会加载补丁,但不会自动请求补丁
        SophixManager.getInstance()
                .setContext(this)
                .setAppVersion(getAppVersionName(this))
                .setSecretMetaData("24839876", "0a2966d074b8261636420f4920ac5460", "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCV5VzIe9X3ux/u25VTDP69/6YB+GzbTWxTLnob7wpMP5H3bYgsIsOPL8JTefsqvPN5bLWuYZbrg2GrTQ6582WCucGEjje/5AHpQdxsVBNGi7C2rVUGEg36L5ZQ0rJVroE96EWLdvojesx48G2FNtKDte0gGmYFvJKSblNIMBF881W6Lm6BHL/MzbCW8deoE5EWQpJeLvyWfIrwLG4e/V40THBqgZqmrtmpb7V3lKXdTQjlxwpy7S2Wy3gm247ASNXTLHLo5V/P4ote5QaL7DKdPHEHj36l2Lp0vSKgzKLe0mc9XaT81GTBoFlZA11PmnyF1ST6QfNFQCB7ZIqqsC/5AgMBAAECggEAeUF0X/3FJcRq3Zcl4WwWum4Ox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uK8/w3Ba1/82+Fve0n6n50Ae58tvu+QM6kELlg7gl14bXiatjelk0rqxbfZ6ducO9s4rf6SLfu666XsvnOap8QHHESB6nDQKzgWoGVQ==")
                .setAesKey(null)//用户自定义aes秘钥, 会对补丁包采用对称加密,补丁工具设置里面AES Key保持完全一致
                .setEnableDebug(false)//查看日志过滤TAG:Sophix,正式发布该参数必须为false
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
                        // 补丁加载回调通知
                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                            // 表明补丁加载成功
                            Timber.e("PatchStatus.CODE_LOAD_SUCCESS handlePatchVersion = " + handlePatchVersion);
                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                            // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
                            // 建议: 用户可以监听进入后台事件, 然后调用killProcessSafely自杀，以此加快应用补丁
                            Timber.e("PatchStatus.CODE_LOAD_RELAUNCH handlePatchVersion = " + handlePatchVersion);
                            ToastUtils.showLongToastSafe("补丁文件已加载完毕,需重启应用");
                            // SophixManager.getInstance().killProcessSafely();
                        } else {
                            // 其它错误信息, 查看PatchStatus类说明
                            Timber.e("code = " + code);
                        }
                    }
                })
                .initialize();
    }

    public static void setDebugFloatWindowShow() {
        try {
            View view = LayoutInflater.from(Global.getContext())
                    .inflate(R.layout.float_window_layout, null);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(Global.getContext(), DebugInfoActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Global.getContext().startActivity(intent);
                }
            });
            FloatWindow.with(Global.getContext())
                    .setView(view)
                    .setWidth(Screen.width, 0.15f)
                    .setHeight(Screen.width, 0.15f)
                    .setX(Screen.width, 0.8f)
                    .setY(Screen.height, 0.8f)
                    .setMoveType(MoveType.back)
                    .setMoveStyle(500, new BounceInterpolator())
                    .setFilter(false, DebugInfoActivity.class)
                    .setDesktopShow(true)
                    .build();
            FloatWindow.get().show();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
